package org.jeecgframework.web.service.impl;

import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.web.service.CbsInspectionEvaluateServiceI;
import org.jeecgframework.web.service.CbsServiceLogServiceI;
import org.jeecgframework.web.service.CbsTechologyAgreeReportServiceI;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.SendMailUtil;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.Serializable;

@Service("cbsTechologyAgreeReportService")
@Transactional
public class CbsTechologyAgreeReportServiceImpl extends CommonServiceImpl implements CbsTechologyAgreeReportServiceI {

    @Autowired
    private CbsInspectionEvaluateServiceI cbsInspectionEvaluateService;
    @Autowired
    private CbsServiceLogServiceI cbsServiceLogServiceI;
    @Autowired
    private SystemService systemService;

    public <T> void delete(T entity) {
        super.delete(entity);
        //执行删除操作配置的sql增强
        this.doDelSql((CbsTechologyAgreeReportEntity) entity);
    }

    public <T> Serializable save(T entity) {
        Serializable t = super.save(entity);
        //执行新增操作配置的sql增强
        this.doAddSql((CbsTechologyAgreeReportEntity) entity);
        return t;
    }

    public <T> void saveOrUpdate(T entity) {
        super.saveOrUpdate(entity);
        //执行更新操作配置的sql增强
        this.doUpdateSql((CbsTechologyAgreeReportEntity) entity);
    }

    /**
     * 默认按钮-sql增强-新增操作
     *
     * @param id
     * @return
     */
    public boolean doAddSql(CbsTechologyAgreeReportEntity t) {
        return true;
    }

    /**
     * 默认按钮-sql增强-更新操作
     *
     * @param id
     * @return
     */
    public boolean doUpdateSql(CbsTechologyAgreeReportEntity t) {
        return true;
    }

    /**
     * 默认按钮-sql增强-删除操作
     *
     * @param id
     * @return
     */
    public boolean doDelSql(CbsTechologyAgreeReportEntity t) {
        return true;
    }

    @Override
    public AjaxJson ZCTechnologyAgree(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        boolean flag = true;
        String message = "技术支持完工单暂存成功";
        CbsTechologyAgreeReportEntity tecAgree = null;
        CbsServiceEntity service = null;
        TSTerritory sheng = null;
        TSTerritory shi = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
            String orderTimeStr = request.getParameter("orderTime");
            String actualTimeStr = request.getParameter("actualTime");
            String finishTimeStr = request.getParameter("closeTime");
            String shengCode = request.getParameter("province");
            String shiCode = request.getParameter("city");
            String serviceId = request.getParameter("serviceId");
            if (serviceId != null && serviceId != "") {
                service = systemService.get(CbsServiceEntity.class, serviceId);
                tecAgree = systemService.singleResult("from CbsTechologyAgreeReportEntity where serviceId.id='" + serviceId + "'");
            }
            if (StringUtil.isNotEmpty(service) && !service.getSpeedStatus().equals("7")) {
                if (tecAgree == null) {
                    tecAgree = new CbsTechologyAgreeReportEntity();
                    tecAgree.setReportCategory(7);
                    tecAgree.setStatus(0);
                    tecAgree.setServiceId(service);
                }
                if (shengCode != null && shengCode != "") {
                    sheng = systemService.singleResult("from TSTerritory where territoryLevel = 1 and territoryCode='" + shengCode + "'");
                }
                if (shiCode != null && shiCode != "") {
                    shi = systemService.singleResult("from TSTerritory where territoryLevel = 2 and territoryCode='" + shiCode + "'");
                }

                //基本信息
                if (orderTimeStr != null && orderTimeStr != "") {
                    tecAgree.setOrderTime(sdf1.parse(orderTimeStr));
                }
                if (actualTimeStr != null && actualTimeStr != "") {
                    tecAgree.setActualTime(sdf.parse(actualTimeStr));
                }
                if (finishTimeStr != null && finishTimeStr != "") {
                    tecAgree.setFinishTime(sdf.parse(finishTimeStr));
                }

                System.out.println("type:" + request.getParameter("esTypeId"));
                if (StringUtil.isNotEmpty(request.getParameter("esTypeId"))) {

                    ZyEquipmentTypeEntity type = systemService.get(ZyEquipmentTypeEntity.class, request.getParameter("esTypeId"));
                    tecAgree.setEquipmentType(type);
                }
                tecAgree.setCinemaName(request.getParameter("zyCinemaName"));
                if (request.getParameter("sceneTotal") != null && !request.getParameter("sceneTotal").equals("")) {
                    tecAgree.setSceneTotal(request.getParameter("sceneTotal"));
                }
                tecAgree.setSheng(sheng);
                tecAgree.setShi(shi);
                tecAgree.setAddress(request.getParameter("address"));
                tecAgree.setTypeIntheaterName(request.getParameter("typename"));
                String contactsName = request.getParameter("contactsName");
                String assignDes = request.getParameter("assignDes");
                tecAgree.setContactsName(contactsName);
                tecAgree.setAssignDes(assignDes);
                tecAgree.setPhone(request.getParameter("phone"));
                tecAgree.setSn(request.getParameter("sn"));
                //现场信息记录
                tecAgree.setServiceDes(request.getParameter("serviceDes"));
                tecAgree.setMemo(request.getParameter("memo"));
                systemService.saveOrUpdate(tecAgree);

            } else {
                flag = false;
                message = "技术支持完工单已完工，请刷新页面";
            }

        } catch (Exception e) {
            message = "技术支持完工单暂存失败";
            flag = false;
            e.printStackTrace();
            System.err.println("事务出现异常,回滚事务！");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//此处采用手动回滚

        }
        j.setMsg(message);
        j.setSuccess(flag);
        return j;
    }

    @Override
    public AjaxJson subTechnologyAgree(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        boolean flag = true;
        CbsTechologyAgreeReportEntity tecAgree = null;
        CbsServiceEntity service = null;
        TSTerritory sheng = null;
        TSTerritory shi = null;
        String message = "技术支持完工单提交成功";
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
            String orderTimeStr = request.getParameter("orderTime");
            String actualTimeStr = request.getParameter("actualTime");
            String finishTimeStr = request.getParameter("closeTime");
            String type1 = request.getParameter("type");
            String serviceId = request.getParameter("serviceId");

            //是否为补填完工单
            Boolean editReport = Boolean.valueOf(oConvertUtils.getString(request.getParameter("editReport")));

            if (StringUtil.isNotEmpty(serviceId)) {
                service = this.get(CbsServiceEntity.class, serviceId);
                //如果是补填完工单 或者 状态不是7
                if (editReport || !service.getSpeedStatus().equals("7")) {
                    if(!editReport){//非 补填完工单时才更新服务单状态（防止影响原状态）
                        systemService.updateBySqlString("update cbs_service set speed_status='" + StaticValue.fwywc + "' where id='" + serviceId + "'");
                    }

                    tecAgree = this.singleResult("from CbsTechologyAgreeReportEntity where serviceId.id='" + serviceId + "'");
                    if (tecAgree == null) {
                        tecAgree = new CbsTechologyAgreeReportEntity();
                        tecAgree.setReportCategory(7);
                        tecAgree.setStatus(0);
                        tecAgree.setServiceId(service);
                    }
                    String shengCode = request.getParameter("province");
                    if (shengCode != null && shengCode != "") {
                        sheng = this.singleResult("from TSTerritory where territoryLevel = 1 and territoryCode='" + shengCode + "'");
                    }
                    String shiCode = request.getParameter("city");
                    if (shiCode != null && shiCode != "") {
                        shi = this.singleResult("from TSTerritory where territoryLevel = 2 and territoryCode='" + shiCode + "'");
                    }
                    //基本信息
                    tecAgree.setReportCategory(7);
                    tecAgree.setStatus(0);
                    tecAgree.setServiceId(service);
                    if (orderTimeStr != null && orderTimeStr != "") {
                        tecAgree.setOrderTime(sdf1.parse(orderTimeStr));
                    }
                    if (actualTimeStr != null && actualTimeStr != "") {
                        tecAgree.setActualTime(sdf.parse(actualTimeStr));
                    }
                    if (finishTimeStr != null && finishTimeStr != "") {
                        tecAgree.setFinishTime(sdf.parse(finishTimeStr));
                    }
                    if (StringUtil.isNotEmpty(request.getParameter("esTypeId"))) {
                        ZyEquipmentTypeEntity type = this.get(ZyEquipmentTypeEntity.class, request.getParameter("esTypeId"));
                        tecAgree.setEquipmentType(type);
                    }
                    tecAgree.setCinemaName(request.getParameter("zyCinemaName"));
                    tecAgree.setSceneTotal(request.getParameter("sceneTotal"));
                    tecAgree.setSheng(sheng);
                    tecAgree.setShi(shi);
                    tecAgree.setAddress(request.getParameter("address"));
                    tecAgree.setTypeIntheaterName(request.getParameter("typename"));
                    tecAgree.setContactsName(request.getParameter("contactsName"));
                    tecAgree.setPhone(request.getParameter("phone"));
                    tecAgree.setSn(request.getParameter("sn"));
                    //现场信息记录
                    tecAgree.setServiceDes(request.getParameter("serviceDes"));
                    tecAgree.setMemo(request.getParameter("memo"));
                    this.saveOrUpdate(tecAgree);

                    //非补填完工单时再进行下边有关于服务单的操作
                    if(!editReport){
                        service.setSpeedStatus("7");
                        service.setReportType(6);
                        service.setReportId(tecAgree.getId());
                        if (type1.equals("2")) {  //HD关单
                            service.setCloseTime(new Date());
                            service.setStatus("4");
                        } else {
                            //判断服务单是否需要HD关单
                            if (service.getHdClose() != null && service.getHdClose() == 1) {
                                //邮件提醒HD进行检查和关单操作
                                String FWS = "";
                                String serviceType = "";
                                if (service != null) {
                                    if (service.getServiceType2() != null) {
                                        serviceType = service.getServiceType2().getName();
                                    }

                                    if (StringUtil.isNotEmpty(service.getServiceProviderCode())) {
                                        TSDepart FWSTs = this.singleResult("from TSDepart where orgCode='" + service.getServiceProviderCode() + "'");
                                        if (FWSTs != null) {
                                            FWS = FWSTs.getDepartname();
                                        }
                                    }
                                }

                                String enginnerName = "";
                                String enginnerPhone = "";
                                if (StringUtil.isNotEmpty(service.getEngineer())) {
                                    ZyEngineerEntity enginner = this.get(ZyEngineerEntity.class, service.getEngineer());
                                    if (enginner != null) {
                                        enginnerName = enginner.getName();
                                        enginnerPhone = enginner.getCellphone();
                                    }
                                }
                                String mailTital = "服务单手动关单通知：<" + FWS + ">-<" + service.getLevel() + ">-<" + serviceType + ">-<" + service.getCode() + ">-<" + service.getZyCinemaName() + ">-" + getDateStr(new Date());
                                String mailContent = "服务单号<" + service.getCode() + ">已完工，需要您审核后手动进行关单操作。如有疑问请联系现场工程师：<" + enginnerName + "><" + enginnerPhone + ">\n" +
                                        "具体内容请查看http://cbs.cfg-barco.com或登陆巴可客服App。\n" +
                                        "【中影巴可客服部】\n" +
                                        "* 该邮件请勿回复";
                                List<TSUser> HDUserList = new ArrayList<>();
                                List<TSRoleUser> tsRoleUserList = this.findHql("from TSRoleUser where TSRole.roleCode='" + StaticValue.CBS_HD_ROLE_CODE + "'");
                                if (null != tsRoleUserList && tsRoleUserList.size() > 0) {
                                    for (TSRoleUser tsRoleUser : tsRoleUserList) {
                                        if (StringUtil.isNotEmpty(tsRoleUser.getTSUser()) && StringUtil.isNotEmpty(tsRoleUser.getTSUser().getStatus()) && tsRoleUser.getTSUser().getStatus().equals(Globals.User_Normal)) { //正常状态的用户
                                            TSUser HDUser = tsRoleUser.getTSUser();
                                            HDUserList.add(HDUser);
                                        }
                                    }
                                }
                                if (HDUserList.size() > 0) {
                                    for (TSUser HDUser : HDUserList) {
                                        if (StringUtil.isNotEmpty(HDUser.getEmail())) {
                                            SendMailUtil.sendeMail(HDUser.getEmail(), mailTital, mailContent, systemService);
                                        }
                                    }
                                }
                            }
                            if (service.getHdClose() == 0) {
                                service.setCloseTime(new Date());
                                service.setStatus("4");
                            }
                        }
                        systemService.saveOrUpdate(service);
                        //判断服务单完工时，是否需要自动创建回访
                        cbsInspectionEvaluateService.assessService(service.getId());
                    }

                    //添加完工报告日志
                    TSUser tsUser = ResourceUtil.getSessionUserName();
                    if(editReport){
                        cbsServiceLogServiceI.addServiceLog(service, StaticValue.Close_Service_Log_Type_2, tsUser.getRealName() + "补填了完工单。", null);
                    } else if (type1.equals("2")) { //HD关单
                        cbsServiceLogServiceI.addServiceLog(service, StaticValue.Close_Service_Log_Type_2, tsUser.getRealName() + "提交了完工报告，并且关闭了服务单。", null);
                    } else {
                        cbsServiceLogServiceI.addServiceLog(service, StaticValue.Close_Service_Log_Type_2, tsUser.getRealName() + "提交了完工报告。", null);
                    }
                } else {
                    flag = false;
                    message = "技术支持完工单第三方已完工，请刷新页面";
                }
            }
        } catch (Exception e) {
            message = "技术支持完工单保存异常";
            flag = false;
            e.printStackTrace();
            System.err.println("事务出现异常,回滚事务！");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//此处采用手动回滚
        }
        j.setMsg(message);
        j.setSuccess(flag);
        return j;
    }

    //当前日期转化为MMdd字符转
    public String getDateStr(Date date) {
        SimpleDateFormat df = new SimpleDateFormat("MMdd");
        String dateStr = df.format(date);
        return dateStr;
    }

    /**
     * 替换sql中的变量
     *
     * @param sql
     * @return
     */
    public String replaceVal(String sql, CbsTechologyAgreeReportEntity t) {
        sql = sql.replace("#{id}", String.valueOf(t.getId()));
        sql = sql.replace("#{report_category}", String.valueOf(t.getReportCategory()));
        sql = sql.replace("#{service_id}", String.valueOf(t.getServiceId()));
        sql = sql.replace("#{scene_total}", String.valueOf(t.getSceneTotal()));
        sql = sql.replace("#{order_time}", String.valueOf(t.getOrderTime()));
        sql = sql.replace("#{actual_time}", String.valueOf(t.getActualTime()));
        sql = sql.replace("#{finish_time}", String.valueOf(t.getFinishTime()));
        sql = sql.replace("#{cinema_name}", String.valueOf(t.getCinemaName()));
        sql = sql.replace("#{type_intheater_name}", String.valueOf(t.getTypeIntheaterName()));
        sql = sql.replace("#{sheng}", String.valueOf(t.getSheng()));
        sql = sql.replace("#{shi}", String.valueOf(t.getShi()));
        sql = sql.replace("#{address}", String.valueOf(t.getAddress()));
        sql = sql.replace("#{contacts_name}", String.valueOf(t.getContactsName()));
        sql = sql.replace("#{phone}", String.valueOf(t.getPhone()));
        sql = sql.replace("#{sn}", String.valueOf(t.getSn()));
        sql = sql.replace("#{equipment_type}", String.valueOf(t.getEquipmentType()));
        sql = sql.replace("#{assign_des}", String.valueOf(t.getAssignDes()));
        sql = sql.replace("#{finish_file}", String.valueOf(t.getFinishFile()));
        sql = sql.replace("#{service_des}", String.valueOf(t.getServiceDes()));
        sql = sql.replace("#{memo}", String.valueOf(t.getMemo()));
        sql = sql.replace("#{status}", String.valueOf(t.getStatus()));
        sql = sql.replace("#{create_name}", String.valueOf(t.getCreateName()));
        sql = sql.replace("#{create_by}", String.valueOf(t.getCreateBy()));
        sql = sql.replace("#{create_date}", String.valueOf(t.getCreateDate()));
        sql = sql.replace("#{update_name}", String.valueOf(t.getUpdateName()));
        sql = sql.replace("#{update_by}", String.valueOf(t.getUpdateBy()));
        sql = sql.replace("#{update_date}", String.valueOf(t.getUpdateDate()));
        sql = sql.replace("#{UUID}", UUID.randomUUID().toString());
        return sql;
    }
}